package com.echo.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.echo.context.WisUserIdContext;
import com.echo.dto.CourseDTO;
import com.echo.entity.*;
import com.echo.mapper.*;
import com.echo.result.ResultVO;
import com.echo.service.ICourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.echo.vo.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 课程信息表 服务实现类
 * </p>
 *
 * @author echo
 * @since 2025-02-23
 */
@Service
@RequiredArgsConstructor
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    private final CourseMapper courseMapper;
    private final ExamRecordMapper examRecordMapper;
    private final QuestionnaireMapper questionnaireMapper;
    private final QuestionnaireQuestionMapper questionnaireQuestionMapper;
    private final ExamMapper examMapper;
    private final WisUserMapper wisUserMapper;
    private final ExamServiceImpl examService;

    // 1.添加课程（保持不变）
    public ResultVO<Integer> createCourse(CourseDTO courseDTO) {
        //添加课程创建者
        String userId = WisUserIdContext.getUserIdContext();
        WisUser wisUser = wisUserMapper.selectById(userId);
        String userNickname = wisUser.getUserNickname();
        Course course=new Course();
        BeanUtils.copyProperties(courseDTO,course);
        course.setCreatorName(userNickname);
        courseMapper.insert(course);
        return ResultVO.success(course.getCourseId());
    }

    // 2.查看所有课程（使用MP方法）
    public ResultVO<List<Course>> getAllCourses() {
        return ResultVO.success(courseMapper.selectList(null));
    }



    // 3.查看课程详情,获得课程大纲、内容等
    public ResultVO<CourseVo> getCourseDetail(Integer courseId) {
        Course course = courseMapper.selectById(courseId);
        if (course == null) {
            return ResultVO.error(404, "课程不存在");
        }
        CourseVo courseVo=new CourseVo();
        BeanUtils.copyProperties(course,courseVo);
/*        Map<String, Object> result = new HashMap<>();
        result.put("course", course);
        result.put("examRecords", examRecordMapper.selectByCourseId(courseId));
        result.put("questionnaires", getQuestionnairesWithDetails(courseId));*/
        return ResultVO.success(courseVo);
    }
    // 4.根据courseid获取对应的试卷列表
    @Override
    public List<ExamRecordVo> getExamRecordsList(Integer courseId) {
        //得到courseId的问题
        QueryWrapper<ExamRecord> examRecordQueryWrapper=new QueryWrapper<>();
        examRecordQueryWrapper.lambda().eq(ExamRecord::getCourseId,courseId);
        // 查询当前课程下的所有记录
        List<ExamRecord> examRecordList = examRecordMapper.selectList(examRecordQueryWrapper);

        // 按 examId 分组，仅保留 exam_join_date 最新的记录
        Map<String, ExamRecord> latestExamRecordMap = new HashMap<>();
        for (ExamRecord record : examRecordList) {
            String examId = record.getExamId();
            if (!latestExamRecordMap.containsKey(examId) ||
                    record.getExamJoinDate().after(latestExamRecordMap.get(examId).getExamJoinDate())) {
                latestExamRecordMap.put(examId, record);
            }
        }

        // 将最新记录转为列表
        List<ExamRecord> latestExamRecordList = new ArrayList<>(latestExamRecordMap.values());

        // 构建返回的 VO 对象列表
        List<ExamRecordVo> examRecordVoList = new ArrayList<>();
        for (ExamRecord examRecord : latestExamRecordList) {
            ExamRecordVo examRecordVo = new ExamRecordVo();
            Exam exam = examMapper.selectById(examRecord.getExamId());
            examRecordVo.setExam(exam);
            String userId = examRecord.getExamJoinerId();
            WisUser wisUser = wisUserMapper.selectById(userId);
            examRecordVo.setWisUser(wisUser);
            examRecordVo.setExamRecord(examRecord);
            examRecordVoList.add(examRecordVo);
        }
        return examRecordVoList;
    }

    //5.1 根据courseid获取对应的所有问卷列表
    @Override
    public List<Questionnaire> getQuestionnairesList(Integer courseId) {
        QueryWrapper<Questionnaire> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(Questionnaire::getCourseId,courseId);
        List<Questionnaire> questionnaireList = questionnaireMapper.selectList(queryWrapper);
        return questionnaireList;
    }
    // 5.2 根据问卷id获得问卷详情
    @Override
    public QuestionnaireVo getQuestionnairesDetail(Integer questionnaireId) {
        QueryWrapper<Questionnaire> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(Questionnaire::getQuestionnaireId,questionnaireId);
        // TODO: 2025/2/25 问卷调查要如何实现
        Questionnaire questionnaire = questionnaireMapper.selectOne(wrapper);
        List<QuestionnaireQuestion> questionnaireQuestionList = parseQuestions(questionnaire);
        QuestionnaireVo questionnaireVo=new QuestionnaireVo();
        BeanUtils.copyProperties(questionnaire,questionnaireVo);
        questionnaireVo.setQuestionnaireQuestionList(questionnaireQuestionList);
        return questionnaireVo;
    }


    private List<Map<String, Object>> getQuestionnairesWithDetails(Integer courseId) {
        return null;
    }

    //5. 根据问卷id获得问卷问题详情
    private List<QuestionnaireQuestion> parseQuestions(Questionnaire q) {
        List<Integer> questionIds = Arrays.stream(q.getQuestionnaireQuestionId().split("-"))
                .map(Integer::parseInt)
                .toList();
        return questionIds.isEmpty() ?
                Collections.emptyList() :
                questionnaireQuestionMapper.selectBatchIds(questionIds);
    }
}
